<template>
  <div class="project-management">
    <div class="page-header">
      <h1 class="page-title">项目管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchText"
          placeholder="搜索项目名称"
          style="width: 220px; margin-right: 16px;"
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button style="margin-left: 8px;" @click="fetchProjects">刷新</el-button>
      </div>
    </div>

    <el-card>
      <!-- 项目种类选择 -->
      <div class="project-category-bar">
        <span class="category-label">项目种类：</span>
        <el-select v-model="selectedCategory" placeholder="请选择项目种类" style="width: 200px;" @change="handleCategoryChange">
          <el-option label="教学项目" value="teaching" />
          <el-option label="科研项目" value="research" />
        </el-select>
      </div>

      <div class="filter-bar">
        <el-select v-model="filterStatus" placeholder="项目状态" style="width: 140px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="申报中" value="申报中" />
          <el-option label="已立项" value="已立项" />
          <el-option label="执行中" value="执行中" />
          <el-option label="结题审核中" value="结题审核中" />
          <el-option label="已结题" value="已结题" />
          <el-option label="已驳回" value="已驳回" />
          <el-option label="延期" value="延期" />
          <el-option label="终止" value="终止" />
        </el-select>
        
        <!-- 教学项目筛选 -->
        <template v-if="selectedCategory === 'teaching'">
          <el-select v-model="filterType" placeholder="项目类型" style="width: 150px; margin-left: 16px;" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="教改项目" value="教改项目" />
            <el-option label="课程建设项目" value="课程建设项目" />
            <el-option label="教材建设项目" value="教材建设项目" />
            <el-option label="实践教学项目" value="实践教学项目" />
          </el-select>
        </template>

        <!-- 科研项目筛选 -->
        <template v-if="selectedCategory === 'research'">
          <el-select v-model="filterType" placeholder="项目类型" style="width: 120px; margin-left: 16px;" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="纵向" value="纵向" />
            <el-option label="横向" value="横向" />
            <el-option label="校级" value="校级" />
          </el-select>
        </template>

        <el-select v-model="filterLevel" placeholder="项目级别" style="width: 120px; margin-left: 16px;" clearable @change="handleFilterChange">
          <el-option label="全部" value="" />
          <el-option label="国家级" value="国家级" />
          <el-option label="省部级" value="省部级" />
          <el-option label="市厅级" value="市厅级" />
          <el-option label="校级" value="校级" />
        </el-select>

        <!-- 科研项目经费筛选 -->
        <template v-if="selectedCategory === 'research'">
          <div class="funding-range" style="margin-left: 16px;">
            <span class="filter-label">经费区间：</span>
            <el-input-number
              v-model="filterFundingMin"
              :min="0"
              :precision="2"
              controls-position="right"
              placeholder="最小值"
              style="width: 120px;"
              @change="handleFilterChange"
            />
            <span style="margin: 0 8px;">-</span>
            <el-input-number
              v-model="filterFundingMax"
              :min="0"
              :precision="2"
              controls-position="right"
              placeholder="最大值"
              style="width: 120px;"
              @change="handleFilterChange"
            />
            <span style="margin-left: 4px;">万元</span>
          </div>
        </template>

        <!-- 负责人筛选（仅管理员端需要） -->
        <el-input
          v-model="filterLeader"
          placeholder="负责人姓名"
          style="width: 150px; margin-left: 16px;"
          clearable
          @keyup.enter="handleSearch"
          @input="handleFilterChange"
        />

        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-left: 16px;"
          clearable
          @change="handleFilterChange"
        />
      </div>

      <!-- 教学项目表格 -->
      <el-table v-if="selectedCategory === 'teaching'" :data="projects" stripe v-loading="loading">
        <el-table-column prop="leaderName" label="负责人" width="100" show-overflow-tooltip />
        <el-table-column prop="name" label="项目名称" min-width="220" show-overflow-tooltip />
        <el-table-column prop="projectType" label="项目类型" width="120" />
        <el-table-column prop="level" label="项目级别" width="100" />
        <el-table-column prop="totalFunding" label="经费总额(万元)" width="140">
          <template #default="{ row }">
            {{ row.totalFunding ? (row.totalFunding / 10000).toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始时间" width="120" />
        <el-table-column prop="endDate" label="结束时间" width="120" />
        <el-table-column prop="status" label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" style="color:#e6a23c;" v-if="row.status==='申报中' || row.status==='结题审核中'" @click="openReview(row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 科研项目表格 -->
      <el-table v-if="selectedCategory === 'research'" :data="projects" stripe v-loading="loading">
        <el-table-column prop="leaderName" label="负责人" width="100" show-overflow-tooltip />
        <el-table-column prop="name" label="项目名称" min-width="220" show-overflow-tooltip />
        <el-table-column prop="projectType" label="项目类型" width="100" />
        <el-table-column prop="subjectCategory" label="学科分类" width="120" show-overflow-tooltip />
        <el-table-column prop="level" label="项目级别" width="100" />
        <el-table-column prop="totalFunding" label="经费总额(万元)" width="140">
          <template #default="{ row }">
            {{ row.totalFunding ? (row.totalFunding / 10000).toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始时间" width="120" />
        <el-table-column prop="endDate" label="结束时间" width="120" />
        <el-table-column prop="status" label="状态" width="110">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" style="color:#e6a23c;" v-if="row.status==='申报中' || row.status==='结题审核中'" @click="openReview(row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框（与教职工端一致的只读视图） -->
    <el-dialog v-model="showViewDialog" title="项目详情" width="800px">
      <div v-if="viewData" class="view-content">
        <el-form label-width="100px" class="view-form">
          <el-form-item label="项目名称">
            <el-input v-model="viewData.name" readonly />
          </el-form-item>

          <el-form-item label="项目编号" v-if="viewData.project_number">
            <el-input v-model="viewData.project_number" readonly />
          </el-form-item>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="项目类型">
                <el-input v-model="viewData.project_type" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目级别">
                <el-input v-model="viewData.level" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 科研项目特有字段 -->
          <el-row v-if="selectedCategory === 'research'" :gutter="16">
            <el-col :span="12">
              <el-form-item label="学科分类">
                <el-input v-model="viewData.subject_category" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经费来源">
                <el-input v-model="viewData.funding_source" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item v-if="selectedCategory === 'research' && viewData.description" label="项目描述">
            <el-input v-model="viewData.description" type="textarea" :rows="3" readonly />
          </el-form-item>

          <el-form-item v-if="viewData.leader_name" label="项目负责人">
            <el-input v-model="viewData.leader_name" readonly />
          </el-form-item>

          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="开始时间">
                <el-input v-model="viewData.start_date" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间">
                <el-input v-model="viewData.end_date" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="项目状态">
            <el-tag :type="getStatusType(viewData.status)">{{ viewData.status }}</el-tag>
          </el-form-item>

          <!-- 审核意见（如果存在） -->
          <el-form-item label="审核意见" v-if="viewData.review_opinion">
            <el-input v-model="viewData.review_opinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <!-- 结题审核意见（如果存在） -->
          <el-form-item label="结题审核意见" v-if="viewData.finish_review_opinion">
            <el-input v-model="viewData.finish_review_opinion" type="textarea" :rows="3" readonly />
          </el-form-item>

          <el-row :gutter="16" v-if="viewData.application_date || viewData.approval_date">
            <el-col :span="12" v-if="viewData.application_date">
              <el-form-item label="申报日期">
                <el-input v-model="viewData.application_date" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="viewData.approval_date">
              <el-form-item label="立项日期">
                <el-input v-model="viewData.approval_date" readonly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="立项部门" v-if="viewData.approval_department">
            <el-input v-model="viewData.approval_department" readonly />
          </el-form-item>

          <!-- 项目成员 -->
          <el-form-item label="项目成员">
            <el-table :data="viewData.members" border size="small" v-if="viewData.members && viewData.members.length">
              <el-table-column prop="staffNo" label="工号" min-width="120" />
              <el-table-column prop="name" label="姓名" min-width="120" />
              <el-table-column prop="department" label="部门" min-width="150" />
              <el-table-column prop="role" label="角色" min-width="100" />
            </el-table>
            <div v-else class="empty-tip">暂无成员信息</div>
          </el-form-item>

          <!-- 经费信息 -->
          <el-form-item label="经费预算">
            <el-table :data="viewData.fundings" border size="small" v-if="viewData.fundings && viewData.fundings.length">
              <el-table-column prop="amount" label="金额(元)" min-width="150">
                <template #default="{ row }">
                  {{ row.amount ? row.amount.toFixed(2) : '0.00' }}
                </template>
              </el-table-column>
              <el-table-column prop="purpose" label="用途" min-width="200" />
            </el-table>
            <div v-if="viewData.fundings && viewData.fundings.length" class="funding-total">
              <span>经费总计：{{ viewData.totalFunding ? viewData.totalFunding.toFixed(2) : '0.00' }} 元</span>
            </div>
            <div v-else class="empty-tip">暂无经费信息</div>
          </el-form-item>

          <!-- 结题信息（如果存在） -->
          <div v-if="viewData.finish_date || viewData.finish_results" class="finish-info-section">
            <el-divider content-position="left">结题信息</el-divider>
            <el-row :gutter="16" v-if="viewData.finish_date">
              <el-col :span="12">
                <el-form-item label="结题日期">
                  <el-input v-model="viewData.finish_date" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="viewData.finish_type">
                <el-form-item label="结题形式">
                  <el-input v-model="viewData.finish_type" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="结题等级" v-if="viewData.finish_level">
              <el-input v-model="viewData.finish_level" readonly />
            </el-form-item>
            <el-form-item label="结题成果" v-if="viewData.finish_results">
              <el-input v-model="viewData.finish_results" type="textarea" :rows="3" readonly />
            </el-form-item>
          </div>

          <!-- 附件列表 -->
          <el-form-item label="项目附件" v-if="viewData.attachments && viewData.attachments.length">
            <el-table :data="viewData.attachments" border size="small">
              <el-table-column prop="file_name" label="文件名" />
              <el-table-column prop="uploaded_at" label="上传时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.uploaded_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row }">
                  <el-button type="text" @click="downloadFile(row)">下载</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showViewDialog = false">关闭</el-button>
      </template>
    </el-dialog>



    <!-- 审核对话框 -->
    <el-dialog v-model="showReviewDialog" title="项目审核" width="600px">
      <div v-if="reviewProject">
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="项目名称">{{ reviewProject.name }}</el-descriptions-item>
          <el-descriptions-item label="项目类型">{{ reviewProject.projectType }}</el-descriptions-item>
          <el-descriptions-item label="项目级别">{{ reviewProject.level }}</el-descriptions-item>
          <el-descriptions-item label="当前状态">{{ reviewProject.status }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <el-form :model="reviewForm" label-width="100px">
        <el-form-item label="审核结果" required>
          <el-radio-group v-model="reviewForm.status">
            <el-radio label="已通过">通过</el-radio>
            <el-radio label="已驳回">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" required>
          <el-input v-model="reviewForm.opinion" type="textarea" :rows="4" placeholder="请输入审核意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showReviewDialog = false">取消</el-button>
        <el-button type="primary" :loading="reviewLoading" @click="submitReview">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Search, Download } from '@element-plus/icons-vue'
import http from '@/utils/request'
import { 
  getTeachingProjects,
  getProjectById,
  downloadAttachment
} from '@/api/teachingProject'
import { 
  getResearchProjects,
  getResearchProjectById
} from '@/api/researchProject'

const loading = ref(false)
const searchText = ref('')
const selectedCategory = ref('teaching') // 默认选择教学项目
const filterStatus = ref('')
const filterType = ref('')
const filterLevel = ref('')
const filterLeader = ref('') // 负责人筛选
const filterFundingMin = ref(null) // 最小经费
const filterFundingMax = ref(null) // 最大经费
const dateRange = ref([])
const projects = ref([])
const totalCount = ref(0)

// 分页
const pagination = reactive({ page: 1, size: 10 })

// 查看
const showViewDialog = ref(false)
const viewData = ref(null)

// 审核
const showReviewDialog = ref(false)
const reviewProject = ref(null)
const reviewLoading = ref(false)
const reviewForm = reactive({ status: '', opinion: '' })



const formatDateTime = (v) => {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return '-' }
}

// 规范化日期为 YYYY-MM-DD（无效返回空字符串）
const normalizeDate = (value) => {
  if (!value) return ''
  try {
    const d = new Date(value)
    if (isNaN(d.getTime())) return ''
    return d.toISOString().slice(0, 10)
  } catch {
    return ''
  }
}

const getStatusType = (status) => {
  const types = { '申报中': 'info', '已立项': 'success', '执行中': 'warning', '结题审核中': 'warning', '已结题': 'success', '已驳回': 'danger', '延期': 'warning', '终止': 'danger' }
  return types[status] || 'info'
}

// 数据加载
const fetchProjects = async () => {
  try {
    loading.value = true
    let response
    
    // 根据选择的项目种类获取数据
    if (selectedCategory.value === 'research') {
      response = await getResearchProjects()
    } else {
      response = await getTeachingProjects()
    }
    
    const list = Array.isArray(response) ? response : (response?.data || [])
    
    // 前端筛选逻辑
    const filtered = list.filter(p => {
      const okName = !searchText.value || (p.name || '').includes(searchText.value)
      const okStatus = !filterStatus.value || p.status === filterStatus.value
      const okType = !filterType.value || p.projectType === filterType.value
      const okLevel = !filterLevel.value || p.level === filterLevel.value
      const okLeader = !filterLeader.value || (p.leaderName || '').includes(filterLeader.value)
      
      // 经费筛选（仅科研项目）
      let okFunding = true
      if (selectedCategory.value === 'research' && (filterFundingMin.value || filterFundingMax.value)) {
        const funding = p.totalFunding ? p.totalFunding / 10000 : 0 // 转换为万元
        if (filterFundingMin.value && funding < filterFundingMin.value) okFunding = false
        if (filterFundingMax.value && funding > filterFundingMax.value) okFunding = false
      }
      
      // 日期范围筛选
      let okDate = true
      if (dateRange.value && dateRange.value.length === 2) {
        const startDate = dateRange.value[0]
        const endDate = dateRange.value[1]
        if (startDate && endDate) {
          const projectStart = p.startDate ? new Date(p.startDate) : null
          const projectEnd = p.endDate ? new Date(p.endDate) : null
          if (projectStart && projectEnd) {
            okDate = projectStart >= startDate && projectEnd <= endDate
          }
        }
      }
      
      return okName && okStatus && okType && okLevel && okLeader && okFunding && okDate
    })
    
    projects.value = filtered
    totalCount.value = filtered.length
  } catch (e) {
    console.error(e)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 项目种类切换
const handleCategoryChange = () => {
  // 清空筛选条件
  filterStatus.value = ''
  filterType.value = ''
  filterLevel.value = ''
  filterLeader.value = ''
  filterFundingMin.value = null
  filterFundingMax.value = null
  dateRange.value = []
  searchText.value = ''
  
  // 重新获取数据
  fetchProjects()
}

// 查看详情
const handleView = async (row) => {
  try {
    loading.value = true
    let response
    
    console.log('开始获取项目详情，项目ID:', row.id, '项目种类:', selectedCategory.value)
    console.log('项目行数据:', row)
    
    // 根据项目种类调用对应的API
    if (selectedCategory.value === 'research') {
      console.log('调用科研项目API:', `/api/research-projects/${row.id}`)
      response = await getResearchProjectById(row.id)
    } else {
      console.log('调用教学项目API:', `/api/projects/${row.id}`)
      response = await getProjectById(row.id)
    }
    
    console.log('API响应:', response)
    
    if (!response) {
      throw new Error('API返回空响应')
    }
    
    // 检查响应状态
    if (response.status === 401) {
      throw new Error('未授权，请重新登录')
    }
    
    if (response.status === 403) {
      throw new Error('权限不足')
    }
    
    if (response.status === 404) {
      throw new Error('项目不存在')
    }
    
    const detail = response?.data || response
    const proj = detail?.project || detail || {}
    
    console.log('项目详情:', proj)
    console.log('完整响应:', detail)
    
    if (!proj.id) {
      throw new Error('项目数据不完整，缺少ID')
    }
    
    // 负责人姓名从项目详情中获取
    const leaderName = detail?.leaderName || proj.leaderName || ''
    
    // 构建视图数据，处理嵌套结构
    viewData.value = {
      id: proj.id,
      name: proj.name || proj.projectName || '未命名项目',
      project_number: proj.projectNumber || proj.project_number || '',
      project_type: proj.projectType || proj.project_type || '',
      subject_category: proj.subjectCategory || proj.subject_category || '', // 科研项目特有
      level: proj.level || '',
      totalFunding: detail?.totalFunding || 0,
      funding_source: proj.fundingSource || proj.funding_source || '', // 科研项目特有
      status: proj.status || '',
      start_date: normalizeDate(proj.startDate || proj.start_date),
      end_date: normalizeDate(proj.endDate || proj.end_date),
      application_date: normalizeDate(proj.applicationDate || proj.application_date),
      approval_date: normalizeDate(proj.approvalDate || proj.approval_date),
      approval_department: proj.approvalDepartment || proj.approval_department || '',
      finish_date: normalizeDate(proj.finishDate || proj.finish_date),
      finish_type: proj.finishType || proj.finish_type || '',
      finish_level: proj.finishLevel || proj.finish_level || '',
      finish_results: proj.finishResults || proj.finish_results || '',
      created_at: proj.createdAt || proj.created_at || '',
      updated_at: proj.updatedAt || proj.updated_at || '',
      leader_name: leaderName, // 负责人姓名
      description: proj.description || '', // 科研项目特有
      members: detail?.members || [],
      fundings: detail?.fundings || [],
      attachments: detail?.attachments || [],
      review_opinion: proj.reviewOpinion || proj.review_opinion || '',
      finish_review_opinion: proj.finishReviewOpinion || proj.finish_review_opinion || ''
    }
    
    console.log('视图数据构建完成:', viewData.value)
    showViewDialog.value = true
  } catch (e) {
    console.error('获取项目详情失败:', e)
    console.error('错误详情:', {
      message: e.message,
      stack: e.stack,
      response: e.response,
      status: e.response?.status,
      data: e.response?.data
    })
    
    let errorMessage = '获取项目信息失败'
    if (e.response?.status === 401) {
      errorMessage = '未授权，请重新登录'
    } else if (e.response?.status === 403) {
      errorMessage = '权限不足'
    } else if (e.response?.status === 404) {
      errorMessage = '项目不存在'
    } else if (e.message) {
      errorMessage = e.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}





// 审核
const openReview = (row) => {
  reviewProject.value = row
  reviewForm.status = ''
  reviewForm.opinion = ''
  showReviewDialog.value = true
}

const submitReview = async () => {
  try {
    if (!reviewForm.status || !reviewForm.opinion) {
      ElMessage.warning('请填写完整的审核信息')
      return
    }
    reviewLoading.value = true
    
    // 根据项目种类选择API
    let apiUrl
    if (selectedCategory.value === 'research') {
      apiUrl = `/api/research-projects/${reviewProject.value.id}/review`
    } else {
      apiUrl = `/api/projects/${reviewProject.value.id}/review`
    }
    
    await http.post(apiUrl, {
      status: reviewForm.status,
      opinion: reviewForm.opinion
    })
    ElMessage.success('审核完成')
    showReviewDialog.value = false
    fetchProjects()
  } catch (e) {
    console.error(e)
    ElMessage.error('审核失败')
  } finally {
    reviewLoading.value = false
  }
}

// 下载文件
const downloadFile = async (attachment) => {
  try {
    await downloadAttachment(attachment.id, attachment.file_name)
    ElMessage.success(`开始下载文件: ${attachment.file_name}`)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 导出/筛选/搜索/分页
const exportData = async () => {
  const { exportAdminData } = await import('@/utils/exportUtils')
  
  const filters = {
    search: searchText.value,
    status: filterStatus.value,
    type: filterType.value,
    level: filterLevel.value
  }
  
  // 根据选择的项目类别确定导出端点
  const endpoint = selectedCategory.value === 'teaching' ? 'teaching-projects' : 'research-projects'
  const filename = selectedCategory.value === 'teaching' ? '教学项目管理列表.xlsx' : '科研项目管理列表.xlsx'
  
  await exportAdminData(endpoint, filters, filename)
}
const handleSearch = () => { pagination.page = 1; fetchProjects() }
const handleFilterChange = () => { pagination.page = 1; fetchProjects() }
const handleSizeChange = (s) => { pagination.size = s; pagination.page = 1; fetchProjects() }
const handleCurrentChange = (p) => { pagination.page = p; fetchProjects() }

onMounted(() => { fetchProjects() })
</script>

<style scoped>
.project-management { max-width: 1400px; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
.page-title { margin: 0; color: #333; font-size: 24px; font-weight: 500; }
.header-actions { display: flex; align-items: center; }
.project-category-bar { 
  margin-bottom: 16px; 
  padding: 16px; 
  background: #f8f9fa; 
  border-radius: 4px; 
  display: flex; 
  align-items: center; 
}
.category-label { 
  font-weight: 500; 
  margin-right: 12px; 
  color: #333; 
}
.filter-bar { 
  margin-bottom: 16px; 
  display: flex; 
  align-items: center; 
  flex-wrap: wrap; 
  gap: 8px; 
}
.funding-range { 
  display: flex; 
  align-items: center; 
}
.filter-label { 
  font-size: 13px; 
  color: #666; 
  margin-right: 8px; 
}
.pagination { display: flex; justify-content: flex-end; margin-top: 16px; }
.view-content { max-height: 500px; overflow-y: auto; }
.detail-section { margin-top: 16px; }
.detail-section h4 { margin: 0 0 8px 0; color: #333; font-size: 14px; font-weight: 500; }
@media (max-width: 768px) {
  .page-header { flex-direction: column; gap: 16px; align-items: stretch; }
  .filter-bar { flex-wrap: wrap; gap: 8px; }
  .filter-bar > * { margin-left: 0 !important; }
  .project-category-bar { flex-direction: column; align-items: flex-start; gap: 8px; }
}
</style>